﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ShareMarking.Service;
using System.Configuration;
using ShareMarking.Entity;
using System.Data;

namespace ShareMarking.SyncActivity
{
    class Program
    {
        static void Main(string[] args)
        {
            string info = "";
            try
            {
                #region 初始化变量
                string httpstr = ConfigurationManager.AppSettings["vigohttp"];        //http://wx.meadjohnson.com.cn/API/Qrcode/index
                string signsecret = ConfigurationManager.AppSettings["signscrect"];  //sdf5sf5et5e42t5
                string diyhttp = ConfigurationManager.AppSettings["diyhttp"];       //本系统网站域名//http://admin.mjn.c2d.me
                var actlist = qr_ActivityService.Instance.Get_AllData_List();//Get_Entity_byWhere(qr_Activity._.A_StartTime != null && qr_Activity._.A_EndTime != null && qr_Activity._.isneedupdate==true, qr_Activity._.ActivityID.Desc);
                ComLib.LogLib.Log4NetBase.Log("1-1、---------------查询所有数据开始！总共" + actlist.Count + "条数据---------------");
                var currenturl = "";
                var currenturl2 = "";
                var currenturl3 = "";
                var currenturl4 = "";
                var currenturl5 = "";
                var ssacode = "";
                var pandstr = "";//改变的URL

                int SuccessCount = 0;//起始更新成功条数
                int ErroCount = 0;//起始更新相同条数
                int DSuccessCount = 0;//单图文更新成功条数
                int DErroCount = 0;//单图文更新失败条数
                int MSuccessCount = 0;//多图文更新成功条数
                int MErroCount = 0;//多图文更新失败条数

                DateTime datetime = DateTime.Now;//当前时间
                List<ShareMarking.Interface.extra> extra = new List<ShareMarking.Interface.extra>();

                ShareMarking.Interface.extra extralist = null;
                ShareMarking.Interface.extra extralist2 = null;
                ShareMarking.Interface.extra extralist3 = null;
                ShareMarking.Interface.extra extralist4 = null;
                ShareMarking.Interface.extra extralist5 = null;
                #endregion

                #region 1、先循环判断每条数据是否需要更新
                for (int i = 0; i < actlist.Count; i++)
                {
                    ComLib.LogLib.Log4NetBase.Log("1-2、---------------正在执行第(" + i + ")条数据---------------");
                    var act = actlist[i];
                    bool result = false;

                    if (act.A_StartTime != null && act.A_EndTime != null)
                    {
                        #region 判断URL
                        if (datetime < act.A_StartTime)
                        {
                            currenturl = act.A_wxbeforeUrl;
                        }
                        else if (datetime > act.A_StartTime && datetime < act.A_EndTime)
                        {
                            currenturl = act.A_wxUrl;
                        }
                        else
                        {
                            currenturl = act.A_wxafterUrl;
                        }
                        #endregion

                        #region 更新URL
                        if (currenturl != act.A_currentUrl)
                        {
                            act.isneedupdate = true;//更改更新状态为true
                            result = qr_ActivityService.Instance.Update_Entity(act);
                        }
                        else
                        {
                            result = false;
                            //ComLib.LogLib.Log4NetBase.Log("1-3、---------------不需要更新为true的活动ID:" + act.ActivityID + "//活动名称:" + act.A_Name + "//当前URL:" + act.A_currentUrl + "//替换的URL：" + currenturl + "---------------");
                        }
                        if (result == true)
                        {
                            SuccessCount += 1;
                            info = "1-3、=========已更新为true的活动ID:" + act.ActivityID + "====活动名称:" + act.A_Name + "====当前URL:" + act.A_currentUrl + "=====替换的URL：" + currenturl + "=========";
                            ComLib.LogLib.Log4NetBase.Log(info);                            
                        }
                        else
                        {
                            ErroCount += 1;
                        }
                        #endregion
                    }
                    else
                    {
                        ErroCount += 1;//没有活动起止时间也失败                           
                        ComLib.LogLib.Log4NetBase.Log("0-0、---------------开始时间或结束时间错误！活动ID:" + act.ActivityID + "//活动开始时间：" + act.A_StartTime + "//活动结束时间:" + act.A_EndTime + "---------------");
                    }
                }
                ComLib.LogLib.Log4NetBase.Log("1-4、---------------设置isneedupdate = true的活动执行完成；更新成功:" + SuccessCount + "条;不需要更新:" + ErroCount + "条---------------");
                 #endregion

                #region 2、获取isneedupdate = true需要更新的数据
                var isneedupdatelist = qr_ActivityService.Instance.Get_Entity_byWhere(qr_Activity._.A_StartTime != null && qr_Activity._.A_EndTime != null && qr_Activity._.isneedupdate == true, qr_Activity._.ActivityID.Asc);//Get_AllData_List();
                ComLib.LogLib.Log4NetBase.Log("=============================================::更新开始::==============================================");
                ComLib.LogLib.Log4NetBase.Log("2-1、---------------更新开始！总共有" + isneedupdatelist.Count + "条需要更新的数据---------------");

                if (isneedupdatelist.Count > 0)
                {
                    for (int i = 0; i < isneedupdatelist.Count; i++)
                    {
                        ComLib.LogLib.Log4NetBase.Log("2-2、---------------正在执行第(" + i + ")条数据---------------");
                        var isupdateact = isneedupdatelist[i];
                        bool result2 = false;

                        var dt = qr_MoreActivityService.Instance.Get_Entity_byWhere_ToTable(qr_MoreActivity._.ActivityID == isupdateact.ActivityID, qr_MoreActivity._.id.Asc);
                        if (dt.Rows.Count > 0)
                        {
                            ComLib.LogLib.Log4NetBase.Log("qr_MoreActivity---------------更新多图文开始！总共有" + dt.Rows.Count + "条需要更新的数据---------------");
                            #region 判断需不需要更新多图文

                            #region 判断URL
                            if (datetime < isupdateact.A_StartTime)
                            {
                                currenturl = isupdateact.A_wxbeforeUrl;
                            }
                            else if (datetime > isupdateact.A_StartTime && datetime < isupdateact.A_EndTime)
                            {
                                currenturl = isupdateact.A_wxUrl;
                            }
                            else
                            {
                                currenturl = isupdateact.A_wxafterUrl;
                            }
                            if (currenturl.Contains("?"))
                            {
                                ssacode = "$sacode=" + isupdateact.A_SaCode;
                            }
                            else
                            {
                                ssacode = "?sacode=" + isupdateact.A_SaCode;
                            }
                            #endregion

                            #region 单图文
                            //if (currenturl != isupdateact.A_currentUrl)
                            //{
                                extralist = new ShareMarking.Interface.extra
                                {
                                    title = isupdateact.A_wxTitle,
                                    shortdesc = isupdateact.A_wxDesc,
                                    linkurl = (currenturl + ssacode).Replace('&', '$'),
                                    picurl = diyhttp + isupdateact.A_wxImgUrl
                                };
                                extra.Add(extralist);
                            //}
                            #endregion

                            #region 追加多图文
                            for (int j = 0; j < dt.Rows.Count; j++)
                            {
                                ComLib.LogLib.Log4NetBase.Log("3-2、---------------多图文正在执行第(" + j + ")条数据---------------");
                                bool result = false;
                               
                                #region 判断URL
                                if (datetime < isupdateact.A_StartTime)
                                {
                                    #region 根据当前时间判断（活动前）URL
                                    if (dt.Rows[j]["MA_Sort"].ToString() == "2")
                                    {
                                        currenturl2 = dt.Rows[j]["MA_wxbeforeUrl"].ToString();
                                        pandstr = currenturl2;//做日志输出使用
                                    }
                                    else if (dt.Rows[j]["MA_Sort"].ToString() == "3")
                                    {
                                        currenturl3 = dt.Rows[j]["MA_wxbeforeUrl"].ToString();
                                        pandstr = currenturl3;//做日志输出使用
                                    }
                                    else if (dt.Rows[j]["MA_Sort"].ToString() == "4")
                                    {
                                        currenturl4 = dt.Rows[j]["MA_wxbeforeUrl"].ToString();
                                        pandstr = currenturl4;//做日志输出使用
                                    }
                                    else if (dt.Rows[j]["MA_Sort"].ToString() == "5")
                                    {
                                        currenturl5 = dt.Rows[j]["MA_wxbeforeUrl"].ToString();
                                        pandstr = currenturl5;//做日志输出使用
                                    }
                                    #endregion
                                }
                                else if (datetime > isupdateact.A_StartTime && datetime < isupdateact.A_EndTime)
                                {
                                    #region 根据当前时间判断（活动中）URL
                                    if (dt.Rows[j]["MA_Sort"].ToString() == "2")
                                    {
                                        currenturl2 = dt.Rows[j]["MA_wxUrl"].ToString();
                                        pandstr = currenturl2;//做日志输出使用
                                    }
                                    else if (dt.Rows[j]["MA_Sort"].ToString() == "3")
                                    {
                                        currenturl3 = dt.Rows[j]["MA_wxUrl"].ToString();
                                        pandstr = currenturl3;//做日志输出使用
                                    }
                                    else if (dt.Rows[j]["MA_Sort"].ToString() == "4")
                                    {
                                        currenturl4 = dt.Rows[j]["MA_wxUrl"].ToString();
                                        pandstr = currenturl4;//做日志输出使用
                                    }
                                    else if (dt.Rows[j]["MA_Sort"].ToString() == "5")
                                    {
                                        currenturl5 = dt.Rows[j]["MA_wxUrl"].ToString();
                                        pandstr = currenturl5;//做日志输出使用
                                    }
                                    #endregion
                                }
                                else
                                {
                                    #region 根据当前时间判断（活动后）URL
                                    if (dt.Rows[j]["MA_Sort"].ToString() == "2")
                                    {
                                        currenturl2 = dt.Rows[j]["MA_wxafterUrl"].ToString();
                                        pandstr = currenturl2;//做日志输出使用
                                    }
                                    else if (dt.Rows[j]["MA_Sort"].ToString() == "3")
                                    {
                                        currenturl3 = dt.Rows[j]["MA_wxafterUrl"].ToString();
                                        pandstr = currenturl3;//做日志输出使用
                                    }
                                    else if (dt.Rows[j]["MA_Sort"].ToString() == "4")
                                    {
                                        currenturl4 = dt.Rows[j]["MA_wxafterUrl"].ToString();
                                        pandstr = currenturl4;//做日志输出使用
                                    }
                                    else if (dt.Rows[j]["MA_Sort"].ToString() == "5")
                                    {
                                        currenturl5 = dt.Rows[j]["MA_wxafterUrl"].ToString();
                                        pandstr = currenturl5;//做日志输出使用
                                    }
                                    #endregion
                                }
                                if (currenturl2.Contains("?") || currenturl3.Contains("?") || currenturl4.Contains("?") || currenturl5.Contains("?"))
                                {
                                    ssacode = "$sacode=" + isupdateact.A_SaCode;
                                }
                                else
                                {
                                    ssacode = "$sacode=" + isupdateact.A_SaCode;
                                }
                                info = "更新多图文活动qr_MoreActivity活动ID:" + dt.Rows[j]["ActivityID"].ToString() + "=====活动名称:" + isupdateact.A_Name + "====当前URL:" + dt.Rows[j]["MA_currentUrl"].ToString()+"=====替换的URL:"+pandstr;
                                #endregion

                                #region 组装消息
                                #region 双图文
                                if (dt.Rows[j]["MA_Sort"].ToString() == "2")
                                {
                                    extralist2 = new ShareMarking.Interface.extra
                                    {
                                        title = dt.Rows[j]["MA_wxTitle"].ToString(),
                                        shortdesc = dt.Rows[j]["MA_wxDesc"].ToString(),
                                        linkurl = (currenturl2 + ssacode).Replace('&', '$'),
                                        picurl = diyhttp + dt.Rows[j]["MA_wxImgUrl"].ToString()
                                    };
                                    extra.Add(extralist2);//追加到集合
                                    if (currenturl2 != dt.Rows[j]["MA_currentUrl"].ToString())
                                    {
                                        #region 更新第二条图文活动
                                        var entity2 = new qr_MoreActivity();
                                        entity2.id = dt.Rows[j]["id"].ConvertTo<int>();
                                        entity2.MA_currentUrl = currenturl2;//当前时间的currurl
                                        entity2.DateModified = DateTime.Now;
                                        result = qr_MoreActivityService.Instance.Update_Entity(entity2);
                                        #endregion                                                                          
                                    }                                    
                                }
                                #endregion

                                #region 三图文
                                else if (dt.Rows[j]["MA_Sort"].ToString() == "3")
                                {
                                    extralist3 = new ShareMarking.Interface.extra
                                    {
                                      title = dt.Rows[j]["MA_wxTitle"].ToString(),
                                      shortdesc = dt.Rows[j]["MA_wxDesc"].ToString(),
                                      linkurl = (currenturl3 + ssacode).Replace('&', '$'),
                                       picurl = diyhttp + dt.Rows[j]["MA_wxImgUrl"].ToString()
                                    };
                                    extra.Add(extralist3);//追加到集合
                                    if (currenturl3 != dt.Rows[j]["MA_currentUrl"].ToString())
                                    {
                                        #region 更新第三条图文活动
                                        var entity3 = new qr_MoreActivity();
                                        entity3.id = dt.Rows[j]["id"].ConvertTo<int>();
                                        entity3.MA_currentUrl = currenturl3;//当前时间的currurl
                                        entity3.DateModified = DateTime.Now;
                                        result = qr_MoreActivityService.Instance.Update_Entity(entity3);
                                        #endregion
                                    }                                    
                                }
                                #endregion

                                #region 四图文
                                else if (dt.Rows[j]["MA_Sort"].ToString() == "4")
                                {
                                    extralist4 = new ShareMarking.Interface.extra
                                    {
                                        title = dt.Rows[j]["MA_wxTitle"].ToString(),
                                        shortdesc = dt.Rows[j]["MA_wxDesc"].ToString(),
                                        linkurl = (currenturl4 + ssacode).Replace('&', '$'),
                                        picurl = diyhttp + dt.Rows[j]["MA_wxImgUrl"].ToString()
                                    };
                                    extra.Add(extralist4);//追加到集合
                                    if (currenturl4 != dt.Rows[j]["MA_currentUrl"].ToString())
                                    {
                                        #region 更新第四条图文活动
                                        var entity4 = new qr_MoreActivity();
                                        entity4.id = dt.Rows[j]["id"].ConvertTo<int>();
                                        entity4.MA_currentUrl = currenturl4;//当前时间的currurl
                                        entity4.DateModified = DateTime.Now;
                                        result = qr_MoreActivityService.Instance.Update_Entity(entity4);
                                        #endregion
                                    }
                                }
                                #endregion

                                #region 五图文
                                else if (dt.Rows[j]["MA_Sort"].ToString() == "5")
                                {
                                    extralist5 = new ShareMarking.Interface.extra
                                    {
                                        title = dt.Rows[j]["MA_wxTitle"].ToString(),
                                        shortdesc = dt.Rows[j]["MA_wxDesc"].ToString(),
                                        linkurl = (currenturl5 + ssacode).Replace('&', '$'),
                                        picurl = diyhttp + dt.Rows[j]["MA_wxImgUrl"].ToString()                              
                                    };
                                    extra.Add(extralist5);//追加到集合
                                    if (currenturl5 != dt.Rows[j]["MA_currentUrl"].ToString())
                                    {
                                        #region 更新第五条图文活动
                                        var entity5 = new qr_MoreActivity();
                                        entity5.id = dt.Rows[j]["id"].ConvertTo<int>();
                                        entity5.DateModified = DateTime.Now;
                                        entity5.MA_currentUrl = currenturl5;//当前时间的currurl
                                        result = qr_MoreActivityService.Instance.Update_Entity(entity5);
                                        #endregion
                                    }                                   
                                }
                                #endregion
                                #endregion

                                if (result == true)
                                {
                                    MSuccessCount += 1;
                                    ComLib.LogLib.Log4NetBase.Log("2-3(Success)---------------多图文更新成功::" + info + "---------------");
                                }
                                else
                                {
                                    MErroCount += 1;
                                    ComLib.LogLib.Log4NetBase.Log("2-3(Error)---------------多图文更新失败::" + info + "---------------");
                                }
                            }
                            #endregion

                            if (extra.Count > 0)//有数据才更新
                            {
                                #region vigo接口申请
                                var message = new ShareMarking.Interface.message2()
                                {
                                    id = isupdateact.A_wxQrCodeID,
                                    title = isupdateact.A_Name,
                                    remark = isupdateact.A_Name + "的二维码",
                                    sacode = "test",
                                    extra = extra
                                };
                                var vigo = new ShareMarking.Interface.Qrcode_vigo(httpstr, signsecret);
                                var resultentity = vigo.UpdateQrcode(message);
                                extra.Clear();//请求后，移除所有图文，重新请求
                                #endregion

                                #region 更新第一条图文活动
                                isupdateact.DateModified = DateTime.Now;
                                isupdateact.A_currentUrl = currenturl;//当前使用的URL
                                isupdateact.isneedupdate = false;
                                qr_ActivityService.Instance.Update_Entity(isupdateact);
                                #endregion
                            }
                            #endregion
                            ComLib.LogLib.Log4NetBase.Log("qr_MoreActivity---------------更新多图文结束！成功" + MSuccessCount + "条；多图文失败" + MErroCount + "条---------------");
                        }
                        else
                        {                            
                            ComLib.LogLib.Log4NetBase.Log("qr_Activity---------------更新单图文开始!---------------");                            
                            #region 判断需不需要更新单图文
                            #region 判断URL
                            if (datetime < isupdateact.A_StartTime)
                            {
                                currenturl = isupdateact.A_wxbeforeUrl;
                            }
                            else if (datetime > isupdateact.A_StartTime && datetime < isupdateact.A_EndTime)
                            {
                                currenturl = isupdateact.A_wxUrl;
                            }
                            else
                            {
                                currenturl = isupdateact.A_wxafterUrl;
                            }
                            info = "更新单图文活动地址为:ID:" + isupdateact.ActivityID + "//活动名称:" + isupdateact.A_Name + "//当前URL:" + isupdateact.A_currentUrl + "//替换的URL:" + currenturl;
                            ComLib.LogLib.Log4NetBase.Log(info);
                            #endregion

                            if (currenturl != isupdateact.A_currentUrl)
                            {
                                //是微信二维码才请求接口
                                if (isupdateact.isSenate == 1)
                                {
                                    #region 组装消息
                                    if (currenturl.Contains("?"))
                                    {
                                        ssacode = "$sacode=" + isupdateact.A_SaCode;
                                    }
                                    else
                                    {
                                        ssacode = "?sacode=" + isupdateact.A_SaCode;
                                    }
                                    extra = new List<ShareMarking.Interface.extra>() { 
                                    new ShareMarking.Interface.extra { 
                                        title = isupdateact.A_wxTitle, 
                                        shortdesc = isupdateact.A_wxDesc, 
                                        linkurl = (currenturl+ssacode).Replace('&','$'),
                                        picurl =diyhttp+ isupdateact.A_wxImgUrl
                                    }
                                };
                                    var message = new ShareMarking.Interface.message2()
                                    {
                                        id = isupdateact.A_wxQrCodeID,
                                        title = isupdateact.A_Name,
                                        remark = isupdateact.A_Name + "的二维码",
                                        sacode = "test",
                                        extra = extra
                                    };
                                    #endregion

                                    #region vigo接口申请
                                    var vigo = new ShareMarking.Interface.Qrcode_vigo(httpstr, signsecret);
                                    var resultentity = vigo.UpdateQrcode(message);
                                    extra.Clear();//请求后，移除所有图文，重新请求
                                    #endregion
                                }
                                else
                                {
                                    #region 普通二维码直接修改即可
                                    if (qr_DiyCodeService.Instance.Get_IsExist_ByWhere(qr_DiyCode._.id == isupdateact.A_wxQrCodeID))
                                    {
                                        #region 修改普通二维码路径
                                        var qr_diyentity = qr_DiyCodeService.Instance.Get_SingleEntity_byWhere(qr_DiyCode._.id == isupdateact.A_wxQrCodeID);
                                        qr_diyentity.source_url = currenturl;//(currenturl + ssacode).Replace('&', '$');//Par_Diy_Url;//跳转的真实url
                                        qr_diyentity.DateModified = DateTime.Now;
                                        qr_DiyCodeService.Instance.Update_Entity(qr_diyentity);
                                        #endregion
                                    }
                                    else 
                                    {
                                        ComLib.LogLib.Log4NetBase.Log("2-3(qr_DiyCode)---------------修改普通二维码失败！::qr_DiyCode-id不存在此记录活动二维码关联ID:" + isupdateact.A_wxQrCodeID + "---------------");
                                    }
                                    #endregion
                                }
                                
                                #region 更新活动前使用的URL
                                isupdateact.DateModified = DateTime.Now;
                                isupdateact.A_currentUrl = currenturl;//当前使用的URL
                                isupdateact.isneedupdate = false;
                                result2 = qr_ActivityService.Instance.Update_Entity(isupdateact);
                                #endregion
                            }
                            else
                            {
                                result2 = false;
                            }
                            if (result2 == true)
                            {
                                DSuccessCount += 1;
                                //ComLib.LogLib.Log4NetBase.Log("2-3(qr_Activity)---------------单图文更新成功::" + info + "---------------");
                            }
                            else
                            {
                                DErroCount += 1;
                                ComLib.LogLib.Log4NetBase.Log("2-3(qr_Activity)---------------单图文更新失败::" + info + "---------------");
                            }
                            #endregion
                            ComLib.LogLib.Log4NetBase.Log("qr_Activity---------------更新单图文结束！成功" + DSuccessCount + "条；单图文失败" + DErroCount + "条---------------");
                        }                      
                    }
                }
                else
                {
                    ComLib.LogLib.Log4NetBase.Log("2-2、---------------当前数据为(" + isneedupdatelist.Count + ")条，没有需要更新的数据---------------");
                }
                ComLib.LogLib.Log4NetBase.Log("=============================================::更新结束::==============================================");
                #endregion
            }
            catch (Exception ex)
            {
                ComLib.LogLib.Log4NetBase.Log("Exception、---------------更新活动错误:" + ex.Message + info + "---------------");
            }
        }
    }
}
